package com.yonyou.base.common.utils;

import com.yonyou.hrcloud.adder.helper.RestServiceHelper;
import org.apache.commons.collections4.MapUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.MediaType;

import java.util.*;

/**
 * 识别API工具类
 */
public class DiscernUtils {

    //应用ID
    private static final String CLIENT_ID = "xu7MBxT2sOiM1GZRXW3iAtGc";
    //引用密钥
    private static final String CLIENT_SECRET = "gcKLuS5WftTl4DFXzI7qetP4cCm80zIS";
    //token获取链接
    private static final String TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";

    private static final String DISCERN_URL = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant";

    /**
     * 获取API访问token
     *
     * @return String token
     */
    public static String getToken() {
        Map<String, Object> params = new HashMap<>();
        params.put("grant_type", "client_credentials");
        params.put("client_id", CLIENT_ID);
        params.put("client_secret", CLIENT_SECRET);
        String str = RestServiceHelper.get(TOKEN_URL, params);
        Map<String, Object> data = JsonHelper.readMapValue(str);
        return MapUtils.getString(data, "access_token");
    }

    /**
     * 识别API调用
     *
     * @param image 图片base64码
     * @return String 识别结果
     */
    public static String getDiscernResult(String image) {
        Map<String, Object> params = new HashMap<>();
        params.put("image", image);
        params.put("baike_num", 3);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        headerMap.put("Accept", "application/json");
        return httpPost(DISCERN_URL + "?access_token=" + getToken(), headerMap, params);
//        return RestServiceHelper.execute(DISCERN_URL + "?access_token=" + getToken(), HttpMethod.POST, params, headerMap);
    }

    public static String httpPost(String url, Map<String, String> headers, Map<String, Object> params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        try {
            //发送http post请求
            HttpPost httpPost = new HttpPost(url);
            //初始化头部信息
            if (headers != null) {
                Set<Map.Entry<String, String>> set = headers.entrySet();
                Iterator<Map.Entry<String, String>> iterator = set.iterator();
                Map.Entry<String, String> entry = null;
                while (iterator.hasNext()) {
                    entry = iterator.next();
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }
            //以form表单的形式提交数据x-www-form-urlencoded
            if (params != null) {
                List<NameValuePair> paramValues = new ArrayList<>();
                Set<Map.Entry<String, Object>> set = params.entrySet();
                Iterator<Map.Entry<String, Object>> iterator = set.iterator();
                Map.Entry<String, Object> entry = null;
                while (iterator.hasNext()) {
                    entry = iterator.next();
                    paramValues.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
                HttpEntity entity = new UrlEncodedFormEntity(paramValues, "UTF-8");
                httpPost.setEntity(entity);
            }
            RequestConfig.custom().setConnectTimeout(80000);
            httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity, "UTF-8");
            }
            return null;
        } catch (Exception e) {
            return null;
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
                httpClient.close();
            } catch (Exception e) {
            }
        }
    }
}
